<!--
  @Description:导航配置编辑
  @Author:zqy
  @Date:2022-12-23 16:20:35
  @Last Modified by:zqy
  @Last Modified time:2022-12-23 16:20:35
-->
<template>
  <el-dialog
    ref="refDlg"
    :title="`${!!(detailData && detailData.id) ? '编辑' : '新增'}导航`"
    :visible.sync="dialogShow"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :hide-func-bar="true"
    :before-close="clearForm"
    width="800px"
    custom-class="custom-dlg"
    @close="closeDialog"
  >
    <div>
      <el-form ref="form" :model="formData" :rules="formRules" size="mini" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="导航名称" prop="tabName">
              <el-input v-model="formData.tabName" size="mini" placeholder="请输入导航名称" maxlength="30" show-word-limit />
            </el-form-item>
          </el-col>
          <template v-if="[0,'0'].includes(tabDefineType)">
            <el-col :span="8">
              <el-form-item label="是否显示" prop="state">
                <el-switch v-model="formData.state" :active-value="1" :inactive-value="0" />
              </el-form-item>
            </el-col>
            <el-col v-if="Number(formData.state || 0) ===1 && isLevelOne" :span="16">
              <el-form-item
                label="显示位置"
                prop="showPlatform"
                :rules="[
                  {required:Number(formData.state || 0) ===1 && isLevelOne,message:'请选择显示位置',trigger:'change'}
                ]"
              >
                <el-select v-model="formData.showPlatform" multiple clearable style="width:100%" disabled>
                  <el-option v-if="defaultPlatform.includes('mobile')" value="mobile" label="移动端" />
                  <el-option v-if="defaultPlatform.includes('pad')" value="pad" label="PAD" />
                  <el-option v-if="defaultPlatform.includes('pc')" value="pc" label="PC端" />
                </el-select>
              </el-form-item>
            </el-col>
          </template>

          <el-col v-if="modifyShowType" :span="24">
            <el-form-item
              label="显示方式"
              prop="showType"
              :rules="[
                {required:modifyShowType,message:'请选择显示方式',trigger:'change'}
              ]"
            >
              <el-select v-model="formData.showType" style="width:200px">
                <el-option :value="1" label="平铺" />
                <el-option :value="2" label="滑动" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="导航图片" prop="picUrl">
              <el-select v-if="formData.levelType==='FIRST' && [0,'0'].includes(tabDefineType)" v-model="formData.picUrl">
                <el-option
                  v-for="(item,i) in iconList"
                  :key="i"
                  :value="item.iconClass"
                  :label="item.name"
                >
                  <div class="navIcon">
                    <span :class="['picIcon','iconfont', item.iconClass]" />
                    <span>{{ item.name }}</span>
                  </div>
                </el-option>
              </el-select>
              <div v-else class="nav-icon-row">
                <qup-img-uploader
                  :width="formData.levelType==='FIRST' && [0,'0'].includes(tabDefineType)?40:100"
                  :height="formData.levelType==='FIRST' && [0,'0'].includes(tabDefineType)?40:100"
                  mask
                  :image-url="cateImage.absoluteUrl"
                  :relative-url="cateImage.relativeUrl"
                  @upload-success="handleUploadSuccess"
                  @remove="handleDelImg"
                />
                <div class="icon-msg">
                  <template v-if="[0,'0'].includes(tabDefineType)">
                    <div v-if="formData.levelType==='FIRST'">一级导航图片尺寸建议40*40</div>
                    <div v-if="formData.levelType==='SECOND'">二级导航图片尺寸建议446*254</div>
                    <div v-if="formData.levelType==='THIRD'">三级导航图片尺寸建议686*360</div>
                    <!-- TODO:四级导航图片大小待定 -->
                    <div v-if="formData.levelType==='FOURTH'">三级导航图片尺寸建议686*360</div>
                  </template>
                  <template v-else>
                    <div>建议图片尺寸：78*78</div>
                  </template>
                  <div>建议图片不超过1M,支持png\jpg\jpeg</div>
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="关联内容:"
              prop="gotoDTO"
              :rules="[
                { required:!!isLastNode, message: '请选择', trigger: 'change' }
              ]"
            >
              <RelateCategory
                ref="formLink"
                v-model="formData.gotoDTO"
                :hide-atlas-child="formData.levelType==='FIRST'"
              />
            </el-form-item>
          </el-col>
          <el-col v-if="formData.gotoDTO && formData.gotoDTO.gotoType ==='GOODS_CENTER_CATEGORY'" :span="24">
            <el-form-item label="商品广告" prop="productAdvertisementDTOList">
              <div class="photo-list">
                <qup-multi-img-uploader
                  ref="refAdUpload"
                  :width="100"
                  :height="100"
                  mask
                  :limit="5"
                  :file-list="uploadImageList"
                  @add="addPhotoHandle"
                  @delete="deletePhotoHandle"
                />
              </div>
              <p style="color:#999">建议上传1M以内图片保证更佳显示效果,建议尺寸：1200 x 300。最多可上传5张图片，可拖拽排序。</p>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div slot="footer">
      <el-button size="mini" @click="closeDialog">取消</el-button>
      <el-button size="mini" type="primary" @click="submitForm">确定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import RelateCategory from '@/components/RelateCategoy'
import QupImgUploader from '@/components/imgUploader'
import Sortable from 'sortablejs'
import QupMultiImgUploader from '@/components/imgUploader/multipleUpload'
import { saveTabConfig } from '@/api/tabConf'
import NAVICONDATA from './NavIcon'
export default {
  name: 'TabConfigEdit',
  components: { QupMultiImgUploader, RelateCategory, QupImgUploader },
  props: {
    visible: {
      type: Boolean,
      default: false,
      required: true
    },
    defaultPlatform: {
      type: Array,
      default: () => ['mobile']
    },
    tabDefineId: {
      // 导航ID
      type: String,
      default: ''
    },
    tabDefineType: {
      // 导航类型：0 首页导航(新导航配置)，1 自定义导航
      type: [String, Number],
      default: ''
    },
    tabDefineLevel: {
      // 导航层级：1-4
      type: [String, Number],
      default: 1
    },
    detailData: {
      type: [String, Object],
      default: ''
    }
  },
  data() {
    return {
      submiting: false,
      iconList: NAVICONDATA,
      formData: {
        tabName: '',
        showType: '',
        parent: '0',
        levelType: 'FIRST', // 层级类型 一级:FIRST 二级:SECOND 三级:THIRD 四级 FOURTH
        state: 1,
        showPlatform: [], // 显示平台： mobile 移动端， pad  PAD端 ， pc PC端
        picUrl: '',
        picName: '',
        gotoDTO: {
          gotoType: '',
          categoryDTOList: [],
          filterId: '',
          gotoValue: '',
          gotoName: ''
        },
        productAdvertisementDTOList: []
      },
      formRules: {
        tabName: [
          { required: true, message: '请输入导航名称', trigger: 'blur' }
        ],
        state: [
          { required: true, message: '请选择是否显示', trigger: 'blur' }
        ]
      },
      cateImage: {
        absoluteUrl: '',
        relativeUrl: ''
      },
      iconImg: {
        absoluteUrl: '',
        relativeUrl: ''
      },
      photoList: []
    }
  },
  computed: {
    dialogShow: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    },
    uploadImageList() {
      return this.photoList.map(v => {
        return {
          id: v.id,
          name: v.fileName,
          fileUrl: v.fileUrl,
          url: this.formatImageUrl(v.fileUrl)
        }
      })
    },
    isLevelOne() {
      return this.formData.levelType === 'FIRST'
    },
    modifyShowType() {
      // 是否允许编辑显示方式
      if ([0, '0'].includes(this.tabDefineType) || [1, '1'].includes(this.tabDefineLevel)) {
        // 首页导航或者一级自定义导航不显示
        return false
      }
      // 只允许二三四级导航的末级可编辑
      let value = ''
      if ([4, '4'].includes(this.tabDefineLevel)) {
        value = 'THIRD'
      } else if ([3, '3'].includes(this.tabDefineLevel)) {
        value = 'SECOND'
      } else if ([2, '2'].includes(this.tabDefineLevel)) {
        value = 'FIRST'
      }
      return this.formData.levelType === value
    },
    isLastNode() {
      // 是否为末级导航
      if ([4, '4'].includes(this.tabDefineLevel)) {
        // 四层导航
        return this.formData.levelType === 'FOURTH'
      } else if ([3, '3'].includes(this.tabDefineLevel)) {
        // 三层导航
        return this.formData.levelType === 'THIRD'
      } else if ([2, '2'].includes(this.tabDefineLevel)) {
        // 二层导航
        return this.formData.levelType === 'SECOND'
      } else if ([1, '1'].includes(this.tabDefineLevel)) {
        // 一层导航
        return this.formData.levelType === 'FIRST'
      }
      return this.formData.levelType === 'FOURTH'
    }
  },
  watch: {

  },
  created() {
    if ([1, '1'].includes(this.tabDefineType)) {
      this.$set(this.formData, 'showPlatform', ['mobile'])
    } else {
      const values = []
      if (this.defaultPlatform.includes('pc')) {
        values.push('pc')
      }
      if (this.defaultPlatform.includes('mobile')) {
        values.push('mobile')
      }
      this.$set(this.formData, 'showPlatform', values)
    }
    if (this.detailData) {
      const { parent, levelType } = this.detailData
      this.formData.parent = parent
      this.formData.levelType = levelType
      if (this.detailData.id) {
        this.initFormData(this.detailData)
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.openDrag()
    })
  },
  methods: {
    initFormData(data) {
      this.formData = {
        tabName: data.tabName || '', // 导航名称,
        showType: data.showType ? Number(data.showType) : '', // 显示方式: 默认0，1 平铺 ， 2 滑动
        parent: data.parent || '0',
        levelType: data.levelType || 'FIRST',
        state: ['1', 1, '0', 0].includes(data.state) ? Number(data.state) : 1,
        showPlatform: data.showPlatform || '',
        picUrl: data.picUrl || '',
        picName: data.picName || '',
        gotoDTO: {
          gotoType: data.gotoType || '',
          categoryDTOList: data.categoryDTOList || [],
          filterId: data.filterId || '',
          gotoValue: data.gotoValue || '',
          gotoName: data.gotoName || ''
        },
        productAdvertisementDTOList: data.productAdvertisementDTOList || []
      }
      if (data.picUrl) {
        this.cateImage = {
          absoluteUrl: this.formatImageUrl(data.picUrl),
          relativeUrl: data.picUrl
        }
      }
      if (data.iconUrl) {
        this.iconImg = {
          absoluteUrl: this.formatImageUrl(data.iconUrl),
          relativeUrl: data.iconUrl
        }
      }
      const list = []
      data.productAdvertisementDTOList && data.productAdvertisementDTOList.forEach((v, i) => {
        list.push({
          fileUrl: v.picUrl,
          sort: v.sort,
          id: v.id
        })
      })
      this.photoList = list
      this.formData.productAdvertisementDTOList = [...list]
    },
    closeDialog() {
      this.dialogShow = false
      this.clearForm()
    },
    clearForm(done) {
      this.formData = {
        tabName: '',
        showType: '',
        levelType: 'FIRST',
        state: 1,
        showPlatform: '',
        picUrl: '',
        picName: '',
        gotoDTO: {
          gotoType: '',
          categoryDTOList: [],
          filterId: '',
          gotoValue: '',
          gotoName: ''
        },
        productAdvertisementDTOList: []
      }
      this.cateImage = {
        absoluteUrl: '',
        relativeUrl: ''
      }
      this.iconImg = {
        absoluteUrl: '',
        relativeUrl: ''
      }
      this.$refs.form && this.$refs.form.clearValidate()
      done && done()
    },
    handleUploadSuccess(res, file, fileList) {
      this.formData.picUrl = res.storeFileName
      this.formData.picName = res.sourceFileName
      this.cateImage = {
        absoluteUrl: res.url,
        relativeUrl: res.storeFileName
      }
    },
    handleDelImg() {
      this.formData.picUrl = ''
      this.formData.picName = ''
      this.cateImage = {
        absoluteUrl: '',
        relativeUrl: ''
      }
    },
    handleUploadIcon(res, file, fileList) {
      this.formData.iconUrl = res.storeFileName
      this.formData.iconName = res.sourceFileName
      this.iconImg = {
        absoluteUrl: res.url,
        relativeUrl: res.storeFileName
      }
    },
    handleDelIcon() {
      this.formData.iconUrl = ''
      this.formData.iconName = ''
      this.iconImg = {
        absoluteUrl: '',
        relativeUrl: ''
      }
    },
    // 新增广告图
    addPhotoHandle(data) {
      this.formData.productAdvertisementDTOList.push(data)
      this.$refs.form.validateField('productAdvertisementDTOList')
    },
    // 移除广告图片
    deletePhotoHandle(data) {
      const index = this.formData.productAdvertisementDTOList.findIndex(v => v.fileUrl === data.fileUrl)
      this.formData.productAdvertisementDTOList.splice(index, 1)
      this.$refs.form.validateField('productAdvertisementDTOList')
    },
    openDrag() {
      const adItem = this.$refs.refAdUpload && this.$refs.refAdUpload.$el && this.$refs.refAdUpload.$el.querySelector('.el-upload-list')
      this.sortable = adItem && Sortable.create(adItem, {
        animation: 180,
        delay: 0,
        multiDrag: false,
        filter: '.el-upload',
        draggable: '.el-upload-list li',
        handle: '.el-upload-list__item',
        ghostClass: 'dragColbg',
        chosenClass: 'dragColbg',
        onEnd: evt => { // 拖动结束
          if (evt.oldIndex === evt.newIndex) return
          // 处理拖动列数据
          const oldItem = this.formData.productAdvertisementDTOList[evt.oldIndex]
          this.formData.productAdvertisementDTOList.splice(evt.oldIndex, 1)
          this.formData.productAdvertisementDTOList.splice(evt.newIndex, 0, oldItem)
        }
      })
    },
    // 提交表单处理
    submitForm() {
      if (this.submiting) return
      this.$refs['form'].validate(async(valid) => {
        if (valid) {
          if (this.isLastNode && this.$refs.formLink) {
            const flag = this.$refs.formLink.validate()
            if (!flag) {
              this.$message.warning('关联内容不能为空')
              return false
            }
          }

          const { gotoDTO } = this.formData

          // 当跳转关联为商品中心类目时,筛选模板必填
          if (gotoDTO.gotoType === 'GOODS_CENTER_CATEGORY') {
            if (!gotoDTO.filterId) {
              this.$message.error('筛选模板必填!')
              return
            }
          }

          let categoryDTOList = []
          if (gotoDTO && gotoDTO.categoryDTOList) {
            categoryDTOList = gotoDTO.categoryDTOList.map(v => {
              return {
                categoryId: v.categoryId,
                categoryName: v.categoryName
              }
            })
          }

          const productAdvertisementDTOList = this.formData.productAdvertisementDTOList.map((v, i) => {
            return {
              id: v.id || '',
              picUrl: v.fileUrl,
              sort: i,
              tabConfigId: (this.detailData && this.detailData.id) || ''
            }
          })

          const showPlatform = this.formData.showPlatform.join(',')

          const formData = {
            ...this.formData,
            ...gotoDTO
          }
          delete formData.gotoDTO
          formData.showPlatform = showPlatform
          formData.categoryDTOList = categoryDTOList
          formData.productAdvertisementDTOList = productAdvertisementDTOList
          formData.v2TabDefineId = this.tabDefineId

          if (this.detailData && this.detailData.id) {
            formData.id = this.detailData.id
          }

          this.submiting = true
          await saveTabConfig(formData).then(res => {
            this.submiting = false
            if (res.success === 1) {
              this.$message.success(`${formData.id ? '编辑' : '新增'}保存成功`)
              this.$emit('success', !!formData.id)
              this.closeDialog()
            }
          }).catch(() => {
            this.submiting = false
          })
        }
      })
    }
  }
}
</script>
<style lang='scss' scoped>
.nav-icon-row{
  display: flex;
  align-items: center;
  .icon-msg{
    line-height: 1.4;
    font-size: 12px;
    color: #999;
    margin-left: 10px;
  }
}
.el-col el-col-11{margin-bottom: 20px;}
.navIcon{
  display: flex;
  align-items: center;
  .picIcon{
    width: 24px;
    height: 24px;
    line-height: 1;
    font-size: 24px;
    // color: #333;
    margin-right: 10px;
  }
}
/deep/ .el-select-dropdown__item.selected .picIcon{
  color:#3DC094;
}
.photo-list{
  display: flex;
  flex-wrap: wrap;
  .item-image{
    position: relative;
    width: 100px;
    height: 100px;
    margin-right: 10px;
    margin-bottom: 10px;
    border: 1px solid #d8d8d8;
    overflow: hidden;
    margin-bottom: 5px;
    .el-image{
      width: 98px;
      height: 98px;
    }
    .btn-del{
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      top:0;
      align-items: center;
      justify-content: center;
      background-color: rgba(0,0,0,0.5);
      font-size: 20px;
      color: #fff;
    }
    &:hover .btn-del{
      visibility:visible;
    }
  }
}
</style>
